package com.yunxin.download.server.infra.utils;

import cn.hutool.core.text.CharSequenceUtil;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.download.server.service.extenal.ExportConfigDTO;
import com.yunxin.download.server.infra.constant.enums.DownloadResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author zero°
 * @since 2023-06-16
 */
@Slf4j
public enum ExportConfigUtils {
    /**
     * 实例
     */
    X;

    private static final String CONFIG_START = "exportConfig#start";

    private static final String CONFIG_END = "exportConfig#end";

    private static final String SQL_START = "methodSql#start";

    private static final String SQL_END = "methodSql#end";

    /**
     * 读取配置文件
     * @param file file
     * @return ExportConfigDTO
     */
    public ExportConfigDTO getConfig(MultipartFile file){
        try (InputStream inputStream = file.getInputStream();
             InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
             BufferedReader br = new BufferedReader(reader)) {
            String readLine;
            StringBuilder sqlBuilder = new StringBuilder();
            StringBuilder configBuilder = new StringBuilder();
            String flagStart = "";
            String flagEnd = "";
            while ((readLine = br.readLine()) != null) {
                if (readLine.equals(CONFIG_START) || readLine.equals(SQL_START)) {
                    flagStart = readLine;
                    //读到开始行  跳转到下一行
                    continue;
                }
                if (readLine.equals(CONFIG_END) || readLine.equals(SQL_END)) {
                    flagEnd = readLine;
                }
                if (flagStart.equals(CONFIG_START) && !flagEnd.equals(CONFIG_END)) {
                    configBuilder.append(readLine);
                }
                if (flagStart.equals(SQL_START) && !flagEnd.equals(SQL_END)) {
                    sqlBuilder.append(readLine);
                }
            }
            final String sql = sqlBuilder.toString();
            final String config = configBuilder.toString();
            if (CharSequenceUtil.isBlank(sql)) {
                throw new BusinessException(DownloadResultCode.SQL_ERROR);
            }
            if (CharSequenceUtil.isBlank(config)) {
                throw new BusinessException(DownloadResultCode.CONFIG_ERROR);
            }
            ExportConfigDTO exportConfigDTO = new ExportConfigDTO();
            exportConfigDTO.setConfig(config);
            exportConfigDTO.setSql(sql);
            return exportConfigDTO;
        } catch (Exception e) {
            log.error("读取配置文件失败,", e);
            throw new BusinessException(DownloadResultCode.READ_FILE_ERROR);
        }
    }


}
